package com.ibitcube.http.api.util;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Map中的必需字段效验
 * 
 * @author 
 * 
 */

public class ParamValidate {
	
	/**
	 * 进行效验数据,异常时抛出EX000000
	 * 
	 * @param param
	 *            需要效验的MAP
	 * @param keys
	 *            参数列表key值.
	 * @throws TranException
	 */
	public static void doing(Map<String, Object> param, String... keys) throws Exception {
		for (String key : keys) {
			if (!param.containsKey(key) || param.get(key) == null || param.get(key).toString().trim().equals("")) {
				throw new Exception("必填字段[" + key + "]效验不通过!");
			}
		}
	}
	
	/**
	 * 进行效验数据,异常时抛出EX000000
	 * 
	 * @param param
	 *            需要效验的MAP
	 * @param keys
	 *            参数列表key值.
	 * @throws TranException
	 */
	public static void serviceDoing(Map<String, Object> param, String... keys) throws Exception {
		for (String key : keys) {
			if (!param.containsKey(key) || param.get(key) == null || param.get(key).toString().trim().equals("")) {
				throw new Exception("参数"+key+"类型效验不通过!");
			}
		}
	}
	/**
	 * @param parameters
	 * @param keys
	 *            需要重组map的key数组
	 * @return LinkedHashMap 按keys数组中的顺序排列
	 */
	public static Map<String, Object> recombinationMap(Map<String, Object> parameters, String... keys) {
		Map<String, Object> results = new LinkedHashMap<String, Object>();
		for (String key : keys) {
			if (parameters.containsKey(key)) {
				results.put(key, parameters.get(key));
			}
		}
		return results;
	}
	
	/**
	 * 进行效验数据,验证是否为数字
	 * 
	 * @param param
	 *            需要效验的MAP
	 * @param keys
	 *            参数列表key值.
	 * @throws TranException
	 */
	public static void isNumeric(Map<String, Object> param, String... keys) throws Exception {
		/**
		 *验证是否为数字
		 */
		Pattern pattern = Pattern.compile("[0-9]*");
		for (String key : keys) {
			Matcher isNum = pattern.matcher(key);
			if (!isNum.matches()) {
				throw new Exception("指定参数非数字！");
			}
		}
	}
}
